﻿
using Refit;
using StackExchange.Redis;
using ZhaoXi.MSACommerce.AuthService.Clients;
using ZhaoXi.MSACommerce.AuthService.Service;
using ZhaoXi.MSACommerce.CommonServiceClient;

namespace ZhaoXi.MSACommerce.AuthService
{
    public static class DependencyInjection
    {
        public static IServiceCollection AddHttpApi(this IServiceCollection services, IConfiguration configuration)
        {
          
           
            ConfigureUserService(services, configuration);

            ConfigureIdentity(services, configuration);

            ConfigureRedis(services, configuration);
            
            return services;
        }

       

        private static void ConfigureUserService(IServiceCollection services, IConfiguration configuration)
        {
            services.AddServiceClient<UserServiceClient>(option =>
            {
                option.LoadBalancingStrategy = LoadBalancingStrategy.RoundRobin;
            }, client =>
            {
                client.Timeout = TimeSpan.FromSeconds(1);
            });
        }

        private static void ConfigureIdentity(IServiceCollection services, IConfiguration configuration)
        {
          
            services.AddScoped<IIdentityService, IdentityService>();//与原来不一致
            services.AddScoped<ITokenService, TokenService>();
            
            var configurationSection = configuration.GetSection( nameof(JwtSettings));
            var jwtSettings = configurationSection.Get<JwtSettings>();
            if (jwtSettings is null) throw new NullReferenceException(nameof(jwtSettings));
            services.Configure<JwtSettings>(configurationSection);
        }

        private static void ConfigureRedis(IServiceCollection services, IConfiguration configuration)
        {
            var redisConn = configuration.GetConnectionString(name: "RedisConnection");
            if (redisConn !=null)
                services.AddSingleton<IConnectionMultiplexer>(ConnectionMultiplexer.Connect(redisConn));
        }
    }
}
